package app

import (
	"fmt"
	"gitee.com/cristiane/web_gin_template/internal/logging"
	"gitee.com/cristiane/web_gin_template/internal/setup"
	"gitee.com/cristiane/web_gin_template/pkg/util/goroutine"
	"gitee.com/cristiane/web_gin_template/vars"
	"gitee.com/kelvins-io/common/log"
	"os"
	"time"
)

// 初始化application--日志部分
func initApplication(application *vars.Application) error {
	const DefaultLoggerRootPath = "./logs"
	const DefaultLoggerLevel = "debug"

	rootPath := DefaultLoggerRootPath
	if vars.LoggerSetting != nil && vars.LoggerSetting.RootPath != "" {
		rootPath = vars.LoggerSetting.RootPath
	}
	loggerLevel := DefaultLoggerLevel
	if vars.LoggerSetting != nil && vars.LoggerSetting.Level != "" {
		loggerLevel = vars.LoggerSetting.Level
	}

	err := log.InitGlobalConfig(rootPath, loggerLevel, application.Name)
	if err != nil {
		return fmt.Errorf("log.InitGlobalConfig: %v", err)
	}

	return nil
}

// 初始化全局配置
func setupCommonVars(application *vars.WEBApplication) error {
	// internal
	if vars.ServerSetting != nil {
		vars.App.EndPort = vars.ServerSetting.EndPort
	}
	if vars.GPoolSetting != nil && vars.GPoolSetting.WorkerNum > 0 && vars.GPoolSetting.JobChanLen > 0 {
		vars.GPool = goroutine.NewPool(vars.GPoolSetting.WorkerNum, vars.GPoolSetting.JobChanLen)
	}

	// logger
	var err error
	vars.ErrorLogger, err = log.GetErrLogger("err")
	if err != nil {
		return err
	}
	vars.BusinessLogger, err = log.GetBusinessLogger("business")
	if err != nil {
		return err
	}
	vars.AccessLogger, err = log.GetAccessLogger("access")
	if err != nil {
		return err
	}
	// mysql
	if vars.MysqlSetting != nil && vars.MysqlSetting.Host != "" {
		vars.DBEngineXORM, err = setup.NewMySQLXORMEngine(vars.MysqlSetting)
		if err != nil {
			return err
		}
		vars.DBEngineGORM, err = setup.NewMySQLGORMEngine(vars.MysqlSetting)
		if err != nil {
			return err
		}
	}
	// redis
	if vars.RedisSetting != nil && vars.RedisSetting.Host != "" {
		vars.RedisPool, err = setup.NewRedis(vars.RedisSetting)
		if err != nil {
			return err
		}
	}
	return nil
}

func appShutdown(application *vars.Application) error {
	if application.StopFunc != nil {
		return application.StopFunc()
	}
	return nil
}

func appPrepareForceExit() {
	time.AfterFunc(10*time.Second, func() {
		logging.Info("App server Shutdown timeout")
		os.Exit(1)
	})
}
